﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ICSharpCode.SharpZipLib.Zip;
using COM.Web;
using ICSharpCode.SharpZipLib.GZip;
using WebApp.Web.Service;
using COM.Data;

namespace WebApp.Web.Controllers
{
    public class PictureController : Controller
    {
        private IUploadFileService uploadFileService = Unity.Instance.GetService<IUploadFileService>();

        [HttpPost]
        public ActionResult Upload(string qqfilename)
        {
            try
            {
                if (Request.Files.Count != 1)
                    throw new ApplicationException("上传文件应有一个文件流.");

                HttpPostedFileBase postFile = Request.Files[0];
                if (postFile.ContentLength == 0)
                    throw new ApplicationException("空文件");

                var fileItemID = this.uploadFileService.UploadFile("Picture", qqfilename, Request.Files[0]);
                return Json(new { success = true, fileItemID = fileItemID }, "application/json");
            }
            catch
            {
                //Todo:记录异常
                var configService = Unity.Instance.GetService<IWebConfigService>();
                if (configService.DeployHostName.ToString().Contains("localhost"))
                    throw;

                return Json(new { success = false, message = "上传失败!" }, "application/json");
            }
        }

        public ActionResult Index(Guid id)
        {
            var filePath = this.uploadFileService.GetFile(id);
            return File(filePath, "image/jpeg", id.ToString() + System.IO.Path.GetExtension(filePath));
        }

        public ActionResult ResizeAsStream(Guid id, int width, int height)
        {
            try
            {
                var filePath = this.uploadFileService.GetFile(id);
                var img = System.Drawing.Image.FromFile(filePath);
                var pictureService = Unity.Instance.GetService<IImageService>();
                var resizeImg = pictureService.ResizePicture(img, width, height);
                var stream = new System.IO.MemoryStream();
                resizeImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                stream.Position = 0;
                return File(stream, "image/jpeg", id.ToString() + System.IO.Path.GetExtension(filePath));
            }
            catch
            {
                var configService = Unity.Instance.GetService<IWebConfigService>();
                if (configService.DeployHostName.ToString().Contains("localhost"))
                    throw;

                return null;
            }
        }


        public ActionResult ResizeAs(Guid id, int width, int height)
        {
            var filePath = this.uploadFileService.GetPicture(id, width, height);
            return File(filePath, "image/jpeg", id.ToString() + System.IO.Path.GetExtension(filePath));
        }

        public ActionResult ResizeAsJson(Guid id, int width, int height)
        {
            var filePath = this.uploadFileService.GetPicture(id, width, height);
            var img = System.Drawing.Image.FromFile(filePath);
            return Json(new { success = true, filePath = string.Format("/Default/Picture/ResizeAs/{0}_{1}_{2}", id, width, height), width = img.Width, height = img.Height }, "application/json", JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 按比例截取图片,然后调整大小,保存
        /// </summary>
        /// <param name="id">图片文件ID</param>
        /// <param name="fileItemId">图片文件ID</param>
        /// <param name="resizeWidth">原图呈现的大小(目标图呈现的大小)</param>
        /// <param name="resizeHeight">原图呈现的大小,可为空</param>
        /// <param name="imgWidth">原图呈现的实际大小,可为空</param>
        /// <param name="imgHeight">原图呈现的实际大小(缓存物理文件大小)</param>
        /// <param name="cutLeft">截取部分位置</param>
        /// <param name="cutTop">截取部分位置</param>
        /// <param name="cutWidth">截取部分大小</param>
        /// <param name="cutHeight">截取部分大小</param>
        /// <returns>截图后并调整大小</returns>
        [HttpPost]
        public ActionResult CutAndResizeAsJson(Guid id, Guid fileItemId, int resizeWidth, int resizeHeight, int imgWidth, int imgHeight, int cutLeft, int cutTop, int cutWidth, int cutHeight)
        {
            if (imgWidth == 0 && imgHeight == 0)
            {
                var filePath = this.uploadFileService.GetPicture(id, resizeWidth, resizeHeight);
                var img = System.Drawing.Image.FromFile(filePath);
                imgWidth = img.Width;
                imgHeight = img.Height;
            }

            //原图
            var sourceFilePath = this.uploadFileService.GetFile(fileItemId);
            var sourceImg = System.Drawing.Image.FromFile(sourceFilePath);
            var sourceWidth = sourceImg.Width;
            var sourceHeight = sourceImg.Height;

            //剪裁
            var rate = (double)imgWidth / (double)sourceWidth;
            var targetLeft = (double)cutLeft / rate;
            var targetTop = (double)cutTop / rate;
            var targetWidth = (double)cutWidth / rate;
            var targetHeight = (double)cutHeight / rate;

            var pictureService = Unity.Instance.GetService<IImageService>();
            var targetImg = pictureService.GetImageCut(sourceImg, (int)targetLeft, (int)targetTop, (int)targetWidth, (int)targetHeight);

            //调整大小
            var resizeImg = pictureService.ResizePicture(targetImg, resizeWidth, resizeHeight);
            var imgFileItemID = this.uploadFileService.SavePicture(resizeImg,string.Format("{0}_{1}_{2}{3}",System.IO.Path.GetFileNameWithoutExtension(sourceFilePath),resizeWidth,resizeHeight,System.IO.Path.GetExtension(sourceFilePath)));
            return Json(new { success = true,fileItemID = imgFileItemID, filePath = string.Format("/Default/Picture/Index/{0}", imgFileItemID), width = resizeImg.Width, height = resizeImg.Height }, "application/json");
            //return Json(new { success = true, fileItemID = imgFileItemID });
        }

    }
}
